/**
 * 
 */
package me.myachievements.web.accessible;

import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;

import me.myachievements.persistence.account.Account;
import me.myachievements.persistence.account.AccountPersistenceManager;

import me.myachievements.web.ErrorPage;
import me.myachievements.web.MyAchievementsSession;
import me.myachievements.web.restricted.account.AccountDetailsPage;

/**
 * @author besseym
 *
 */
public class LoginForm extends StatelessForm<LoginForm> {
	
	@SpringBean(name="accountPersistenceManager")
	AccountPersistenceManager accountPersistenceManager;
	
	private String username;

	/**
	 * Constructor
	 * @param id
	 */
	public LoginForm(String id) {
		super(id);
		setDefaultModel(new CompoundPropertyModel<LoginForm>(this));
		add(new TextField<String>("username").setRequired(true).add(StringValidator.maximumLength(50)));
	}
	
	@Override
	protected void onSubmit(){
		
		if(logIn(username)){
			if (!continueToOriginalDestination()) {
				setResponsePage(new AccountDetailsPage());
			}
		}
		else{
			error("Unknown username/ password");
			setResponsePage(new IndexPage());
		}
		
	}
	
	private boolean logIn(String username){
		
		if(username != null && !"".equals(username.trim())){
			
			Account account = accountPersistenceManager.get(username);
			if(account != null){
				MyAchievementsSession.get().setAccount(account);
				return true;
			}
		}
		
		return false;
	}

}
